package com.fyyg.redis.common;

import redis.clients.jedis.ShardedJedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class RedisUtil  {  

	/**
	 * 在集合中读取最右边的事件ID 
	 * @param jedis
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String rpopEventList(ShardedJedis jedis,String key) throws Exception{
		String uid = null;
		if((null==key) || (null==jedis)){
			return null;
		}
		uid = jedis.rpop(key);
		if(null!=uid){
			return uid;
		}
		return uid;
	}
	
	/**
	 * 在集合中最左边插入一个事件ID
	 * @param jedis
	 * @param key
	 * @param val
	 * @throws Exception
	 */
	public static void lpushEventList(ShardedJedis jedis,String key,String val) throws Exception{
		if( (null==key) || (null==jedis) || (null==val) || (val.trim().length()<1) ){
			return;
		}else{
			jedis.lpush(key,val);
		}
	}


	/**
	 * 随机从setName中删除num个值并返回
	 * @param jedis
	 * @param setName
	 * @param num
	 * @return
     * @throws Exception
     */
	public static List<String> spopSet(ShardedJedis jedis, String setName, Integer num) throws Exception{
		if( (null==setName) || (null==jedis) ){
			return null;
		}else{
			num = num == null ? 1 : num;
			List<String> list = new ArrayList<>();
			for (Integer i = 0; i < num; i++) {
				list.add(jedis.spop(setName));
			}
			return list;
		}
	}

	/**
	 * 向集合setName中添加多个值
	 * @param jedis
	 * @param setName
	 * @param values
	 * @return
     * @throws Exception
     */
	public static Long saddSet(ShardedJedis jedis,String setName,String... values) throws Exception{
		if( (null==setName) || (null==jedis) || (values == null || values.length <= 0)){
			return null;
		}else{
			return jedis.sadd(setName,values);
		}
	}

	/**
	 * 清空set中的所有数据
	 * @param jedis
	 * @param setName
	 * @return
	 * @throws Exception
     */
	public static Long sResetSet(ShardedJedis jedis,String setName) throws Exception{
		if( (null==setName) || (null==jedis)){
			return null;
		}else{
			Set<String> sets = jedis.smembers(setName);
			if(sets == null || sets.size() <= 0 ){
				return 0L;
			}
			String[] members = new String[sets.size()];
			members = sets.toArray(members);
			return jedis.srem(setName,members);
		}
	}



}  